// pages/shop/foodtype/list.js
var util = require('../../../utils/util.js')
Page({
  data: {
    types: [
      { id: 1, name: "凉菜", snum: 2, state: 1 },
      { id: 2, name: "热菜", snum: 3, state: 1, state:0},
    ],
    foodtype:{},
    istrue:false,
    innum:-1,
  },
  onLoad: function () {
    this.getlist();
  },
  getlist: function () {
    var that=this;
    var url = util.url.shop_food_typelist;
    util.fetchGet(
      url,
      function(ret){
        var list=ret.data;
        that.sortlist(list);
      }
    )
  },
  sortlist:function(list){
    list.sort(function(a,b){
      return b.snum-a.snum;
    })
    this.setData({
      types:list
    })
  },
  addFoodType: function () {
    var that=this;
    var url = util.url.shop_food_typeadd;
    var data=this.data.foodtype;
    util.fetchPost(
      url,
      data,
      function(ret){
        var types = that.data.types;
        var foodtype=ret.data;
        if (data.id && data.id!=0){
          types.splice(that.data.innum, 1, foodtype);
        }else{
          types.push(foodtype); 
        }
        that.sortlist(types);
        that.closeDialog();
      }
    )
  },
  openDialog: function (e) {
    var id=e.currentTarget.dataset.id;
    if (id!=0){
      var types = this.data.types;
      for(var i=0;i<types.length;i++){
        if (id == types[i].id){
          this.setData({
            foodtype: types[i],
            innum:i
          })
          break;
        }
      }
    }else{
      this.setData({
        foodtype: {}
      })
    }
    this.setData({
      istrue: true
    })
  },
  closeDialog: function () {
    this.setData({
      istrue: false
    })
  },
  radioChange:function(e){
    var state = e.detail.value;
    this.setData({
      'foodtype.state': state
    })
  },
  bindTypeNum:function(e){
    var snum = e.detail.value;
    this.setData({
      'foodtype.snum': snum
    })
  },
  bindTypeName:function(e){
    var name = e.detail.value;
    this.setData({
      'foodtype.name': name
    })
  }

})